<template>
  <div style="height:97vh" ref="HexinBox" @click="blurEmoji">
        <!-- 预览遮盖曾 -->
        <div class="dialog" v-show="showDialog">
          <div class="goBack" @click="showDialog = false">返回</div>
          <div class="publish" @click="commit">发表</div>
          <h2>{{title}}</h2>
          <div class="dialog-content" v-html="detailContent"></div>
        </div>

        <header class="bar-top">
          <div class="title">文章发布</div>
          <div class="Hexin-top-btn">
            <div class="preview" @click="showDialog = true">预览</div>
            <!-- <div class="publish">发表</div> -->
          </div>
        </header>
        <input class="Hexin-title" type="text" v-model="title" placeholder="起个引人关注的标题" maxlength="25">
        <!-- 标题的图片显示 -->
          <div class="bar-title">
            <input hidden type="file" accept="image/png,image/gif,image/jpeg" ref="inputTitle">
            <div v-show="formdata.titleImgPath" class="imageBox">
              <img ref="titleImage" src="" alt="">
              <span @click="reChoose">X</span>
            </div>
            <div class="image-choose" v-show="!formdata.titleImgPath" @click="handleTitleImage">
              <span>封面</span>
              <i class="iconfont icon-webicon310"></i>
            </div>
          </div>
        <!-- 前端上传图片压缩大小 -->
        <input hidden class="HexinUploader" type="file" accept="image/png,image/gif,image/jpeg" ref="inputFile" @change="quillUpdateImg = true">
        <!--富文本编辑器组件-->
        <el-row v-loading="quillUpdateImg" style="margin-top:20px">
          <quill-editor
                  v-model="detailContent"
                  ref="HexinEditor"
                  :options="editorOption"
                  @change="onEditorChange($event)"
                  @ready="onEditorReady($event)"
          >
          </quill-editor>
        </el-row>
    <el-footer>
      <!-- emoji表情面板 -->
      <div class="emojiBox" v-show="showEmoji">
        <el-tabs tab-position  value="face">
          <el-tab-pane name="face">
            <span slot="label">😀</span>
            <div class="emojiOneArea-tab" @click="clickEmoji">
              <span class="emojibtn" v-for="(item, index) in emoji.face" :key="index"><span v-html="item"></span></span>
            </div>
          </el-tab-pane>
          <el-tab-pane name="person">
            <span slot="label">👦</span>
            <div class="emojiOneArea-tab" @click="clickEmoji">
              <span class="emojibtn" v-for="(item, index) in emoji.person" :key="index"><span v-html="item"></span></span>
            </div>
          </el-tab-pane>
          <!-- <el-tab-pane name="gesture">
            <span slot="label">✌</span>
            <div class="emojiOneArea-tab" @click="clickEmoji">
              <span class="emojibtn" v-for="(item, index) in emoji.gesture" :key="index"><span v-html="item"></span></span>
            </div>
          </el-tab-pane> -->
          <el-tab-pane name="daily">
            <span slot="label">👀</span>
            <div class="emojiOneArea-tab" @click="clickEmoji">
              <span class="emojibtn" v-for="(item, index) in emoji.daily" :key="index"><span v-html="item"></span></span>
            </div>
          </el-tab-pane>
          <el-tab-pane name="animal">
            <span slot="label">🙈</span>
            <div class="emojiOneArea-tab" @click="clickEmoji">
              <span class="emojibtn" v-for="(item, index) in emoji.animal" :key="index"><span v-html="item"></span></span>
            </div>
          </el-tab-pane>
          <el-tab-pane name="food">
            <span slot="label">🍇</span>
            <div class="emojiOneArea-tab" @click="clickEmoji">
              <span class="emojibtn" v-for="(item, index) in emoji.food" :key="index"><span v-html="item"></span></span>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <el-row type="flex" justify="end">
        <i  @click="doToggleEmoji" class="iconfont icon-xiaolian" style="font-size:2rem"></i>
        <i  @click="btnImg" class="iconfont icon-Group-" style="font-size:2.5rem;margin-top:-0.3rem;margin-left:1rem"></i>
      </el-row>
    </el-footer>
  </div>
</template>

<script>

import doveReduce from '@/api/doveReduce'

const toolbarOptions = [
  [{'header': 2}],
  ['image']
]
export default {
  name: 'HexinEditor',
  data () {
    return {
      quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画，刚开始是false,不显示
      serverUrl: 'http://www.godlike.top/back-end/API/image/acceptOneImage.php', //  这里写你要上传的图片服务器地址
      detailContent: '', // 富文本内容
      title: '', // 标题
      editorOption: {
        placeholder: '分享心得，引发思考，内容越吸引人，越会获得朋友们的关注哦',
        theme: 'bubble',
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏,若没有工具栏，会出现默认的全部工具栏。所以取舍之下，提供了两个按钮
            handlers: {
              'image': function (value) {
                if (value) {
                  document.querySelector('.HexinUploader').click()
                } else {
                  this.quill.format('image', false)
                }
              }}}
        }
      }, //  富文本编辑器配置
      emoji: {
        face: [
          `😀`, `😁`, `😂`, `😃`, `😄`, `😅`, `😆`, `😉`, `😊`, `😋`, `😎`, `😍`, `😘`, `😗`,
          `😙`, `😚`, `😇`, `😐`, `😑`, `😶`, `😏`, `😣`, `😥`, `😮`, `😯`, `😪`, `😫`, `😴`,
          `😌`, `😛`, `😜`, `😝`, `😒`, `😓`, `😔`, `😕`, `😲`, `😷`, `😖`, `😞`, `😟`, `😤`,
          `😢`, `😭`, `😦`, `😧`, `😨`, `😬`, `😰`, `😱`, `😳`, `😵`, `😡`, `😠`, `😈`, `👿`,
          `👹`, `👺`, `💀`, `👻`, `👽`],
        person: [
          `👦`, `👧`, `👨`, `👩`, `👴`, `👵`, `👶`, `👱`, `👮`, `👲`, `👳`, `👷`, `👸`, `💂`,
          `🎅`, `👰`, `👼`, `💆`, `💇`, `🙍`, `🙎`, `🙅`, `🙆`, `💁`, `🙋`, `🙇`, `🙌`, `🙏`,
          `👤`, `👥`, `🚶`, `🏃`, `👯`, `💃`, `👫`, `👬`, `👭`, `💏`, `💑`, `👪`],
        // gesture: [
        //   `💪`, `👈`, `👉`, `☝`, `👆`, `👇`, `✌`, `✋`, `👌`, `👍`, `👎`, `✊`, `👊`, `👋`,
        //   `👏`, `👐`, `✍`],
        daily: [
          `👣`, `👀`, `👂`, `👃`, `👅`, `👄`, `💋`, `👓`, `👔`, `👕`, `👖`, `👗`, `👘`, `👙`,
          `👚`, `👛`, `👜`, `👝`, `🎒`, `💼`, `👞`, `👟`, `👠`, `👡`, `👢`, `👑`, `👒`, `🎩`,
          `🎓`, `💄`, `💅`, `💍`, `🌂`],
        animal: [
          `🙈`, `🙉`, `🙊`, `🐵`, `🐒`, `🐶`, `🐕`, `🐩`, `🐺`, `🐱`, `😺`, `😸`, `😹`, `😻`,
          `😼`, `😽`, `🙀`, `😿`, `😾`, `🐈`, `🐯`, `🐅`, `🐆`, `🐴`, `🐎`, `🐮`, `🐂`, `🐃`,
          `🐄`, `🐷`, `🐖`, `🐗`, `🐽`, `🐏`, `🐑`, `🐐`, `🐪`, `🐫`, `🐘`, `🐭`, `🐁`, `🐀`,
          `🐹`, `🐰`, `🐇`, `🐻`, `🐨`, `🐼`, `🐾`, `🐔`, `🐓`, `🐣`, `🐤`, `🐥`, `🐦`, `🐧`,
          `🐸`, `🐊`, `🐢`, `🐍`, `🐲`, `🐉`, `🐳`, `🐋`, `🐬`, `🐟`, `🐠`, `🐡`, `🐙`, `🐚`,
          `🐌`, `🐛`, `🐜`, `🐝`, `🐞`],
        food: [
          `🍇`, `🍈`, `🍉`, `🍊`, `🍋`, `🍌`, `🍍`, `🍎`, `🍏`, `🍐`, `🍑`, `🍒`, `🍓`, `🍅`,
          `🍆`, `🌽`, `🍄`, `🌰`, `🍞`, `🍖`, `🍗`, `🍔`, `🍟`, `🍕`, `🍳`, `🍲`, `🍱`, `🍘`,
          `🍙`, `🍚`, `🍛`, `🍜`, `🍝`, `🍠`, `🍢`, `🍣`, `🍤`, `🍥`, `🍡`, `🍦`, `🍧`, `🍨`,
          `🍩`, `🍪`, `🍰`, `🍫`, `🍬`, `🍭`, `🍮`, `🍯`, `🍼`, `☕`, `🍵`, `🍶`, `🍷`, `🍸`,
          `🍹`, `🍺`, `🍻`, `🍴`]
      },
      showEmoji: false, //  是否显示表情面板
      showDialog: false, // 是否预览

      formdata: {
        content: this.detailContent,
        title: this.title,
        publisherId: 12,
        type: 1,
        publishState: 1,
        titleImgPath: null,
        publisherName: 'jhkjlk;kjoj',
        contentAbstract: 'jkljkl;l',
        labelList: [
          {id: '000012'}
        ]
      }
    }
  },
  created () {
    this.protect() // 神兽保护
  },
  mounted () {
    doveReduce.init(this.$refs['inputFile'], this.serverUrl, this.callback) //  文章图片初始化
    doveReduce.init(this.$refs['inputTitle'], this.serverUrl, this.titleImageCallBack) //  标题初始化
  },
  methods: {

    callback (res) {
      // 因为调用的是原生js的change事件所以如果重复上传一张图片不会触发，所以，现在进行优化
      this.$refs.inputFile.value = ''
      let sTop = document.body.scrollTop + document.documentElement.scrollTop
      // res为图片服务器返回的数据
      // 获取富文本组件实例
      let quill = this.$refs.HexinEditor.quill
      // 如果上传成功
      if (res.url !== null) {
        // 获取光标所在位置
        // let length = quill.getSelection().index  这个获取方法如果没有内容，则会报错
        let length = quill.selection.savedRange.index || quill.getLength()
        quill.insertText(length, `\n`)
        // 插入图片  res.url为服务器返回的图片地址,这里长度减一是因为换行，接受图片服务器返回格式自己控制，随意
        quill.insertEmbed(length + 1, 'image', res.url)
        quill.insertText(length + 2, `\n`)
        // 调整光标到最后
        quill.setSelection(length + 3)
        // 这里有个问题，为什么图片不会触发IOS的键盘事件
      } else {
        this.$message.error('图片插入失败')
      }
      // loading动画消失
      // BUG 从服务器下载图片需要时间。这个时间段图片是不会显示的
      this.quillUpdateImg = false

      window.scrollTo(0, sTop)
    }, // 图片上传成功的回调函数

    titleImageCallBack (res) {
      console.log(res)
      if (res.url) {
        this.$refs.titleImage.src = res.url
        this.formdata.titleImgPath = res.url
      }
    }, // 封面回调函数

    clickEmoji (event) {
      if (event.target.nodeName === 'DIV') {
        return
      } //  这个方法是判断用户是否点击了表情间的间隙，下面的InnerText如果换成InnerHtml会有问题

      let sTop = document.body.scrollTop + document.documentElement.scrollTop

      let content = event.target.innerText
      // 获取富文本组件实例
      let quill = this.$refs.HexinEditor.quill
      // 获取光标所在位置,index为当前位置，getlength为所有长度,若长度为0会取第二个值，这个bug是||运算符的，目前没想到答案
      let length = quill.selection.savedRange.index || quill.getLength()
      quill.insertText(length, content)
      // 调整光标到最后
      // quill.setSelection(length + 2)
      // document.activeElement.blur() 会触发IOS端的键盘弹出事件。现在把光标事件取消，反正重新出入需要手动弹出输入框，若用API输入则会自动找到最后位置

      window.scrollTo(0, sTop)
    }, //  emoji表情点击事件添加进富文本中,使用事件委托增加性能

    reChoose () {
      this.$refs.inputTitle.value = ''
      this.formdata.titleImgPath = null
      this.$refs.titleImage.src = ''
    }, // 封面图片重新选择

    doToggleEmoji () {
      this.showEmoji = !this.showEmoji
    }, // 显示隐藏表情面板

    blurEmoji (e) {
      if (e.target.nodeName !== `SPAN` && e.target.className.indexOf('iconfont') !== 0) {
        this.showEmoji = false
      }
    }, // 表情面板遗失焦点

    handleTitleImage () {
      this.$refs.inputTitle.click()
    }, // 文章封面

    commit () {
      // 这里因为公司项目会有别的提示组件，所以先暂用原生Alert，方面以后直接替换
      if (!this.title) {
        alert('不要忘记标题呢！')
        return
      }
      if (!this.formdata.titleImgPath) {
        alert('不要忘记封面呢！')
        return
      }
      // 亲们提交网址自己改啊
      this.$http.post('***', this.formdata)
        .then(function (res) {
          console.log(res)
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    btnImg () {
      document.querySelector('.HexinUploader').click()
    },

    onEditorChange (event) {},
    onEditorReady (event) {},

    protect () {
      console.log(`
          * Code is far away from bug with the animal protecting 
          * 
          *----------Dragon be here!----------/ 
          *    ┏┓   ┏┓ 
          *   ┏┛┻━━━┛┻┓ 
          *   ┃       ┃ 
          *   ┃   ━   ┃ 
          *   ┃ ┳┛ ┗┳ ┃ 
          *   ┃       ┃ 
          *   ┃   ┻   ┃ 
          *   ┃       ┃ 
          *   ┗━┓   ┏━┛ 
          *     ┃   ┃神兽保佑 
          *     ┃   ┃代码无BUG！ 
          *     ┃   ┗━━━┓ 
          *     ┃       ┣┓ 
          *     ┃       ┏┛ 
          *     ┗┓┓┏━┳┓┏┛ 
          *      ┃┫┫ ┃┫┫ 
          *      ┗┻┛ ┗┻┛ 
          * ━━━━━━神兽出没━━━━━━ 
          */  
      `)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
/* 因为要考虑兼容高度问题，目前没有精力解决，初步找到了一个适合大部分屏幕的高度 */
.quill-editor >>>.ql-editor{
  min-height: 10rem;
  max-height: 58vh;
  overflow: auto;
}

/* 这里想面板可以滑动的。 */

.bar-top{
  position: relative;
  box-sizing: border-box;
  border-bottom: 1px solid #ccc;
  height: 2.5rem;
  line-height: 2.5rem;
}

.bar-title{
  /* border: 1px solid red; */
  height: 4rem;
  line-height: 4rem;
  position: relative;
}
.image-choose{
  margin-top: 2px;
  margin-left: 2px;
  height: 4rem;
  border: 1px dashed #aaa;
  border-radius: 5px;
  width: 4rem;
}
.image-choose span{
  display: block;
  height: 2rem;
  line-height: 2rem;
  margin-left: 1rem;
  color: #aaa;
}
.imageBox{
  box-sizing: border-box;
  /* height: 60px; */
}
.imageBox>img{
  position: absolute;
  left: 1rem;
  top: 5px;
  width: 80px;
  height: 60px;
}
.imageBox>span{
  color: #666;
  position: absolute;
  left: 82px;
  line-height: 10px;
  top: 10px;
}

.icon-webicon310{
  position: absolute;
  left: 1.25rem;
  top: 1rem;
  font-size: 2rem;
  height: 2rem;
  color: #aaa;
}

.title{
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  font-weight: bold;
  letter-spacing: 0.1rem;
}

.Hexin-top-btn{
  float: right;
  margin-right: 1rem;
  display: flex;
  font-size: 0.9rem;
  color: #aaa;
}

.Hexin-top-btn .publish{
  margin-left: 0.55rem;
}

.Hexin-title{
  outline: none;
  border: none;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid #ccc;
  height: 3rem;
  line-height: 3rem;
  font-size: 24px;
  padding-left: 0.45rem;
}
.Hexin-title::-webkit-input-placeholder{
  letter-spacing: 0.05rem;
}

.el-footer{
  position: fixed;
  bottom: 0rem;
  right: 1rem;
}

.emojiBox{
  position: fixed;
  bottom: 4rem;
  left: 1.5rem;
  height: 200px;
  width: 85vw;
  border: 1px solid #ccc;
  border-radius: 3px;
  overflow: hidden;
  background-color: white;
}

.emojiOneArea-tab{
  box-sizing: border-box;
  padding: 0px 4px 0px 4px;
  height: 140px;
  overflow: auto;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.emojibtn{
  width: 9.6vw;
  height: 9.6vw;
  line-height: 30px;
  font-size: 1.5rem;
  display: block;
  margin: 1px;
  padding: 3px;
  /* border: 1px solid red; */
  text-align: center;
}

.dialog{
  height: 100vh;
  width: 100vw;
  overflow: auto;
  background: white;
  position: fixed;
  z-index: 1;
}
.dialog h2{
  text-align: center;
}
.dialog .goBack{
  position: absolute;
  color: #666;
}
.dialog .publish{
  position: absolute;
  right: 1rem;
  color: #666;
}
</style>
